<template>
    <div class="page-container">
        <el-backtop :right="100" :bottom="100" ref="refBackTop" :visibility-height="100" target=".el-main"></el-backtop>
        <!-- 头部 -->
        <div class="page-filter">
            <!-- 用户状态 -->
            <el-select v-model="filterModel.status" class="m-2" placeholder="请选择用户状态">
                <el-option v-for="item in statusDic" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
            <!-- 用户会员等级 -->
            <el-select v-model="filterModel.level" class="m-2" placeholder="请选择用户会员等级">
                <el-option v-for="item in levelDic" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
            <!-- 用户性别 -->
            <el-select v-model="filterModel.gender" class="m-2" placeholder="请选择用户性别">
                <el-option v-for="item in genderDic" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
            <el-input v-model="filterModel.id" placeholder="请输入用户ID" clearable @input="handleId"/>
            <el-input v-model="filterModel.nickname" placeholder="请输入用户昵称" clearable />
            <el-button type="primary" :icon="Search" @click="handleSearchMember">查找</el-button>
        </div>
        <!-- 数据表格 -->
        <div class="page-table">
            <el-table :data="memberList" border style="width: 100%" v-loading="loading" element-loading-text="拼命加载中...">
                <el-table-column prop="id" label="用户ID" width="80" align="center" />
                <el-table-column prop="nickname" label="昵称" align="center" />
                <el-table-column prop="phone" label="手机号码" align="center" />
                <el-table-column label="性别" align="center" width="80">
                    <template #default="scope">
                        <el-tag v-if="scope.row.gender === 1">女</el-tag>
                        <el-tag v-else-if="scope.row.gender === 2">男</el-tag>
                        <el-tag v-else>未知</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="level" label="会员等级" align="center" width="120">
                    <template #default="scope">
                        <el-tag type="info" v-if="scope.row.level === 0">普通会员</el-tag>
                        <el-tag type="info" v-else class="vip">VIP会员</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="生日" align="center">
                    <template #default="scope">
                        {{ scope.row.birthday ? moment(scope.row.birthday).format('YYYY年MM月DD日') : '-' }}
                    </template>
                </el-table-column>
                <el-table-column label="状态" align="center" width="80">
                    <template #default="scope">
                        <el-tag type="danger" v-if="scope.row.status === 0">冻结</el-tag>
                        <el-tag v-else>激活</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="gmtLastLogin" label="上次登录时间" align="center">
                    <template #default="scope">
                        {{ friendTime(scope.row.gmtLastLogin) }}
                    </template>
                </el-table-column>
                <el-table-column prop="lastLoginIp" label="上次登录IP" align="center" />
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <el-button type="primary" @click="handleEditStatus(scope.row)">{{ scope.row.status ? '冻结' : '激活'
                        }}</el-button>
                        <el-button type="primary" @click="handleOpenDialog(scope.row)" v-permission="'user:user:edit'">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页 -->
        <div style="overflow: hidden;">
            <Pagination v-bind="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <!-- 编辑对话框 -->
        <el-dialog v-model="dialogFormVisible" title="编辑" @close="handleClose">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px">
                <el-form-item label="用户昵称" prop="nickname">
                    <el-input v-model="ruleForm.nickname" />
                </el-form-item>
                <el-form-item label="用户手机号" prop="phone">
                    <el-input v-model="ruleForm.phone" />
                </el-form-item>
                <el-form-item label="用户性别" prop="gender">
                    <el-select v-model="ruleForm.gender" class="m-2" placeholder="请选择用户性别">
                        <el-option v-for="item in editGender" :disabled="item.value==-1" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="用户等级" prop="level">
                    <el-select v-model="ruleForm.level" class="m-2" placeholder="请选择用户会员等级">
                        <el-option v-for="item in editLevel" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="用户状态" prop="status">
                    <el-select v-model="ruleForm.status" class="m-2" placeholder="请选择用户状态">
                        <el-option v-for="item in editStatus" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item style="position:absolute;bottom:10px;right:20px;">
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        确定
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { post } from '@/utils/http';
import { ClassPagination, ClassUser } from '#/index';
import { ElMessage, ElBacktop } from 'element-plus';
import { friendTime } from '@/utils/DateFormatter';
import type { FormInstance, FormRules } from 'element-plus'
import moment from 'moment';

//用户状态
const statusDic = [{ value: 0, name: "冻结" }, { value: 1, name: "激活" }, { value: "", name: "全部" }]
//用户会员等级
const levelDic = [{ value: 0, name: "普通会员" }, { value: 1, name: "VIP会员" }, { value: "", name: "全部" }]
//用户性别
const genderDic = [{ value: 1, name: "女" }, { value: 2, name: "男" }, { value: -1, name: '未知' }, { value: "", name: "全部" }]
//编辑中的下拉框
const editStatus = statusDic.slice(0, 2)
const editLevel = levelDic.slice(0, 2)
const editGender = genderDic.slice(0, 3)
/**
 * 过滤条件对象
 */
const filterModel = reactive({
    nickname: undefined,
    id: undefined,
    status: undefined,
    level: undefined,
    gender: undefined
})
//分页对象
const pagination = reactive(new ClassPagination())
//会员对象
const memberList = ref([{} as ClassUser])
//是否显示正在加载
let loading = ref(false)
// 返回顶部组件节点
const refBackTop = ref()
//编辑对话框
const dialogFormVisible = ref(false)
//form表单节点
const ruleFormRef = ref<FormInstance>()
//form表单对象
const ruleForm = reactive(new ClassUser())
//form表单校验规则
const rules = reactive<FormRules>({
    nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
    phone: [{ required: true, pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, message: '请输入正确的手机格式', trigger: 'blur' }],
    gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
    level: [{ required: true, message: '请选择会员等级', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'blur' }]
})
/**
 * 生命周期
 */
onMounted(() => {
    getMemberList()
})
/**
 * 获取会员数据列表
 */
function getMemberList() {
    loading.value = true
    const data = { _gp: 'admin.user', _mt: 'list', pageNo: pagination.currentPage, limit: pagination.pageSize,
                    ...filterModel }
    post(data).then(res => {
        console.log(res)
        const { data, errmsg, errno } = res
        if (200 === errno) {
            const { total, items } = data
            memberList.value = items
            pagination.total = total
            nextTick(() => {
                refBackTop.value.$el.click?.()
                loading.value = false
            })
        } else {
            ElMessage.error(errmsg)
        }
    })
}
/**
 * 改变一页多少行,防止多次请求
 * @param value 一页多少行
 */
function handleSizeChange(value: number) {
    let tempCurrent = Math.ceil(pagination.total / value)
    if (tempCurrent < pagination.currentPage) {
        pagination.currentPage = tempCurrent
    }
    pagination.pageSize = value
    getMemberList()
}

/**
 * 改变当前页
 * @param value 当前页数
 */
function handleCurrentChange(value: number) {
    pagination.currentPage = value
    getMemberList()
}
/**
 * 解冻激活
 * @param row 当前行对象
 */
function handleEditStatus(row: ClassUser) {
    let { id: userId, status } = row
    status = status == 1 ? 0 : 1
    const data = { _gp: 'admin.user', _mt: 'editStatus', userId, status }
    post(data).then(res => {
        const { errno } = res
        if (200 === errno) {
            ElMessage.success('设置成功')
            getMemberList()
        } else {
            ElMessage.error('设置失败')
        }
    })
}
/**
 * 打开编辑对话框
 * @param row 当前行对象
 */
function handleOpenDialog(row: ClassUser) {
    dialogFormVisible.value = true
    Object.assign(ruleForm, row)
    console.log(ruleForm)
}
/**
 * 编辑确定
 * @param formEl form表单对象
 */
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            const data = { _gp: 'admin.user', _mt: 'edit', user: JSON.stringify(ruleForm) }
            post(data).then(res => {
                console.log(res)
                const { errno ,errmsg} = res
                if (200 === errno) {
                    ElMessage.success('修改成功')
                    dialogFormVisible.value = false
                    getMemberList()
                } else {
                    ElMessage.error(errmsg)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
/**
 * 编辑取消
 * @param formEl form表单对象
 */
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    dialogFormVisible.value = false
    Object.assign(ruleForm, new ClassUser())
}
/**
 * 根据过滤对象查询
 */
function handleSearchMember(){
    getMemberList()
}
/**
 * 格式化id文本搜索框
 */
function handleId(){
    let reg = /^\d+$/
    if(!reg.test(filterModel.id+'')){
        filterModel.id = undefined
    }
}
/**
 * 关闭对话框时的回调
 */
function handleClose(){
    ruleFormRef.value?.resetFields()
}
</script>
<style lang="less" scoped>
.page-filter {
    display: flex;

    &>.el-input {
        width: 180px;
        margin-right: 10px;
    }

    &>.el-select {
        width: 180px;
        margin-right: 10px;
    }
}

.vip :deep(.el-tag__content) {
    color: orange;
}
:deep(.el-dialog__body) {
    padding-bottom: 40px;
}

</style>